<?php

namespace app\modules\admin\controllers;

use app\constants\Code;
use app\extensions\XUtils;
use app\models\Admin;
use app\models\Group;
use app\services\AdminService;
use app\services\CommonService;
use yii;
use yii\data\Pagination;

/**
 * 用户控制器
 * @author chenym
 * @since 2017.7.4
 * Class AdminController
 * @package app\modules\admin\controllers
 */
class AdminController extends BaseController
{
    public function init()
    {
        parent::init();
    }

    public function beforeAction($action)
    {
        //$this->enableCsrfValidation = false;//前端自定义表单时，要关闭csrf验证，否则会找不到显示400 Bad Request
        return parent::beforeAction($action); // TODO: Change the autogenerated stub1
    }

    /**
     * 用户列表
     */
    public function actionIndex()
    {
        $page       = Yii::$app->request->get('page', 1);
        $adminModel = new Admin();
        $groupModel = new Group();
        $userName   = Yii::$app->request->get("userName", "");

        $condition = $params = [];
        if (!empty($userName)) {
            $condition = ['like', 'userName', '%' . $userName . '%', false];
        }
        $fields = [
            'id',
            'userName',
            'statusIs',
            'email',
            'realName',
            'groupId',
        ];
        $adminList = $adminModel::find()->asArray()->where($condition)->orderBy('id')->offset(Code::ADMIN_PAGE_SIZE * ($page - 1))->limit(Code::ADMIN_PAGE_SIZE)->all();
        $total     = $adminModel::find()->where($condition)->count();

        foreach ($adminList as $k => $adminData) {

            $group                      = $groupModel::find()->asArray()->select('groupName')->where(['id' => $adminData["groupId"]])->one();
            $adminList[$k]["groupName"] = $group["groupName"];
        }
        $pages  = new Pagination(['totalCount' => $total, 'pageSize' => Code::ADMIN_PAGE_SIZE]);
        $assign = [
            'pages'    => $pages,
            "userName" => $userName,
            'dataList' => $adminList,
        ];
        return $this->render('index', $assign);
    }

    /**
     * 添加or编辑用户
     */
    public function actionCreate()
    {
        $id            = intval(Yii::$app->request->get('id', 0));
        $groupModel    = new Group();
        $adminService  = new AdminService();
        $adminModel    = new Admin();
        $commonService = new CommonService();
        $adminModel->setScenario('update');
        //用户组所有数据
        $groupList = $groupModel::find()->asArray()->select(["id", "groupName"])->all();

        $check = [];
        if ($id) {
            //$check = $adminModel->dbGet("*", "", ["where" => ["id" => $id]]);
            $check = $adminModel::find()->asArray()->where(['id' => $id])->one();
            if (empty($check)) {
                XUtils::message("error", "用户不存在，请重试！", "/admin/admin/index");
            }

        }
        $assign = [
            'id'        => $id,
            'data'      => $check,
            'groupList' => $groupList,
            'model'     => $adminModel,
        ];
        if (Yii::$app->request->isPost) {
            $Admin                 = Yii::$app->request->post('Admin');
            $adminData['groupId']  = $Admin['groupId'];
            $adminData['realName'] = $Admin['realName'];
            $adminData['statusIs'] = $Admin['statusIs'];
            $adminData['email']    = $Admin['email'];
            $adminData['isLock']   = $Admin['isLock'];
            $userId                = $Admin['id'];
            $userName              = $Admin['userName'];
            $checkUser             = $adminService->checkUserNameIsExists($userName, $userId);
            if ($checkUser) {
                XUtils::message("error", "用户已存在，请重试！", ($userId ? "/admin/admin/create?id={$userId}" : "/admin/admin/create"));
            }

            if ($userId) {
                //编辑用户
                $adminData['updateTime'] = time();
                //判断用户是否有更改过登录名，如更改过则一定要更改密码，否则密码不变
                $checkUser = $adminModel::findOne($userId);
                $checkUser->setScenario('update');
                if ($checkUser->userName != $Admin['userName'] && empty($Admin['password'])) {
                    XUtils::message("error", "您已改动用户名，请填写密码！", "/admin/admin/create?id={$userId}");
                } elseif ($checkUser->userName != $Admin['userName'] && !empty($Admin['password'])) {
                    if ($commonService->passwordValidator($Admin['password']) < 3) {
                        XUtils::message("error", '密码不能小于6个字符或者全为数字或者全为字母,且必须包含“/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]”特殊字符！', "/admin/admin/create?id={$userId}");
                    } else {
                        $adminData['userName'] = $Admin['userName'];
                        $adminData['password'] = $adminService->hashPassword($adminData['userName'], $Admin['password']);
                    }
                } elseif (!empty($Admin['password'])) {
                    $adminData['userName'] = $Admin['userName'];
                    $adminData['password'] = $adminService->hashPassword($adminData['userName'], $Admin['password']);
                    echo $adminData['password'] . "<br/>";
                }

                $checkUser->attributes = $adminData;
                $affect                = $checkUser->save();

            } else {
                //新增用户
                $adminData['createTime'] = $adminData['updateTime'] = time();
                $adminData['userName']   = $Admin['userName'];
                $password                = $Admin['password'];
                $adminData['password']   = $adminService->hashPassword($adminData['userName'], $password);
                $adminModel->attributes  = $adminData;
                $affect                  = $adminModel->save();

            }
            XUtils::message(($affect ? "success" : "error"), ($userId ? "编辑" : "新增") . ($affect ? "成功" : "失败"), "index");
        }
        return $this->render('create', $assign);
    }

    /**
     * 删除用户
     */
    public function actionDelete()
    {
        $id     = Yii::$app->request->post("id", 0);
        $return = AdminService::deleteUser($id);
        exit(XUtils::echoJson($return));
    }
    /**
     * 用户中心
     */
    public function actionUsercenter()
    {
        $groupId = Yii::$app->session->get('_adminiGroupId');
        $userId  = Yii::$app->session->get('_adminiUserId');

        if (Yii::$app->request->isPost) {
            $Admin = Yii::$app->request->post('Admin');

            $id    = $Admin['id'];
            $model = Admin::findOne($userId);
            $model->setScenario('update');
            $password        = $Admin['password'];
            $model->realName = $Admin['realName'];
            $model->email    = $Admin['email'];

            $commonService = new CommonService();
            if ($password) {
                if ($commonService->passwordValidator($password) < 3) {
                    XUtils::message('error', '密码不能小于6个字符或者全为数字或者全为字母,且必须包含“/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]”特殊字符！', "/admin/admin/create?id={$userId}");
                } else {
                    $model->password = $adminService->hashPassword($model->realName, $password);
                }
            }
            $model->updateTime = time();
            $res               = $model->save();

            XUtils::message(($res ? 'success' : 'error'), '修改个人信息成功', '/admin/default/index');
        }
        $model     = new Admin();
        $data      = $model->findOne($userId)->toArray();
        $gmodel    = new Group();
        $groupId   = 1;
        $groupInfo = $gmodel->findOne($groupId)->toArray();

        return $this->render('usercenter', ["data" => $data, 'groupInfo' => $groupInfo, 'id' => 3]);
    }

}
